package rpt

import (
	"context"
	"fmt"
	"gitee.com/alex_li/amazon-rpt/cmd/rpt/process/common"
	"gitee.com/alex_li/amazon-rpt/cmd/rpt/tpl"
	"gitee.com/alex_li/amazon-rpt/internal/db"
	"gitee.com/alex_li/amazon-rpt/internal/rpt"
	"gitee.com/alex_li/amazon-rpt/internal/sdk/advertising"
	"github.com/lishimeng/app-starter"
	"github.com/lishimeng/go-log"
	"time"
)

// 创建报表

func SubmitRpt(ctx context.Context) {
	//var err error
	//var clientIndex int
	//var client db.AmazonLwa
	for {
		select {
		case <-ctx.Done():
			return
		case <-time.After(10 * time.Second):
			report, err := getRpt4Submit()
			if err != nil {
				//log.Info(err)
				break
			}
			result, err := submitRpt(ctx, report)
			if err != nil {
				log.Info(err)
				failSubmit(report, result, err)
			}
		}
	}
}

func getRpt4Submit() (report db.AmazonRpt, err error) {
	var list []db.AmazonRpt
	_, err = app.GetOrm().Context.
		QueryTable(new(db.AmazonRpt)).
		Filter("Status", db.RptStatusInit).
		Limit(1).
		All(&list)
	if err != nil {
		log.Info(err)
		return
	}
	if len(list) == 0 {
		err = fmt.Errorf("no rpt wait for submit")
		return
	}
	report = list[0]
	return
}

func submitRpt(_ context.Context, report db.AmazonRpt) (res advertising.RptStatus, err error) {

	log.Info("submit rpt: %s", report.Name)
	rptTpl, err := tpl.GetTpl(report.RptTemplateId)
	if err != nil {
		log.Info("no rpt template: %s", report.RptTemplateId)
		log.Info(err)
		return
	}
	client, err := common.GetMyClient(report.ClientId)
	if err != nil {
		log.Info("unknown lwa client: %s", report.ClientId)
		log.Info(err)
		return
	}
	req := rpt.GenReq(report.StartDate, report.EndDate, rptTpl, report)

	sdk, err := common.CreateSdk(client)
	if err != nil {
		log.Info(err)
		return
	}
	res, err = sdk.CreateReport(req)
	if err != nil {
		log.Info(err)
		return
	}
	log.Info("create rpt success")
	log.Info("%v", res)
	successSubmit(res, report)

	return
}

func failSubmit(report db.AmazonRpt, status advertising.RptStatus, err error) {
	report.Status = db.RptStatusFail
	report.Memo = fmt.Sprintf("%s%s", status.ErrorInfo.Code, status.Detail)
	_, err = app.GetOrm().Context.Update(&report, "status", "memo")
	if err != nil {
		log.Info("update rpt failed: status<-%s", "failed")
		log.Info(err)
	}
}

func successSubmit(status advertising.RptStatus, report db.AmazonRpt) {
	report.Status = db.RptStatusSubmit
	report.Memo = "-"

	report.RptId = status.ReportId
	report.RptState = status.Status
	report.RptCreateAt = status.CreatedAt
	report.RptUpdateAt = status.UpdatedAt
	report.AmazonRptDuration.StartDate = status.StartDate
	report.AmazonRptDuration.EndDate = status.EndDate
	report.AmazonRptFile.RptFileUrl = status.Url
	report.AmazonRptFile.RptFileSize = status.FileSize
	report.AmazonRptFile.RptFileExpireAt = status.UrlExpiresAt

	report.RptFailureReason = status.FailureReason

	_, err := app.GetOrm().Context.Update(&report)
	if err != nil {
		log.Info("update rpt failed: status<-%s", "failed")
		log.Info(err)
	}
	log.Info("update rpt: status<-%s", "submit")
}
